package com.example.demo.exception;

import com.example.demo.result.CodeMsg;
import com.example.demo.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 相当于一个controller
 * @author 17996
 *
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    //拦截什么异常
    @ExceptionHandler(value=Exception.class)//拦截所有的异常
    public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
        e.printStackTrace();

        /*全局异常处理*/
        if(e instanceof GlobalException) {
            GlobalException ex=(GlobalException) e;
            //	CodeMsg cm=ex.getCm();
            CodeMsg cm=new CodeMsg( 1, ex.getScm()  );

            return Result.error(cm);
        }


        if(e instanceof BindException) { //是绑定异常的情况
            //强转
            BindException ex=(BindException) e;
            //获取错误信息
            List<ObjectError> errors=ex.getAllErrors();
            ObjectError error=errors.get(0);
            String msg=error.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else {  //不是绑定异常的情况
            logger.error( "异常的情况:"+ e.getMessage());
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }
}
